package com.tepth.busfix.network;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.tepth.busfix.MyApplication;
import com.tepth.busfix.tools.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author zhangyu
 * @date 2016/6/15
 */
public class Network {
    private static ApiService apiService;

    private static final Converter.Factory GSON_CONVERTER_FACTORY = retrofit2.converter.gson.GsonConverterFactory.create();
    private static final CallAdapter.Factory RX_JAVA_2_CALL_ADAPTER_FACTORY = RxJava2CallAdapterFactory.create();


    public static ApiService getApiService() {
        if (apiService == null) {
            apiService = getRetrofit().create(ApiService.class);
        }
        return apiService;
    }


    private static Retrofit getRetrofit() {
        return getRetrofit(SPUtils.getBoolean(MyApplication.getContext(), "isDebug"));
    }

    private static Retrofit getRetrofit(boolean isDebug) {
        return new Retrofit.Builder()
                .baseUrl(isDebug ? ApiUrl.DEBUG_BASE_URL : ApiUrl.BASE_URL)
                .callFactory(OkHttpUtils.getInstance().getOkHttpClient())
                .addConverterFactory(GSON_CONVERTER_FACTORY)
                .addCallAdapterFactory(RX_JAVA_2_CALL_ADAPTER_FACTORY)
                .build();

    }

    public static void changeForDebug(boolean isDebug) {
        apiService = null;
        apiService = getRetrofit(isDebug).create(ApiService.class);
    }
}
